import React, { PureComponent, Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import {
  Button,
  Tag,
  Modal,
  Form,
  message,
  Table,
  Radio,
  Input,
  Icon,
  Drawer,
  Row,
  Col,
  Switch,
  Progress, Select,Calendar,Typography,Badge
} from 'antd';
import MyPagination from '@/components/MyPagination';
import Loading from '@/components/Loading';

import find from 'lodash/find';

import debounce from 'lodash/debounce';
import { ellipsis, afterCloseModal, DescriptionItem } from '@/utils/utils';
import { routerRedux } from 'dva/router';
import BuildModalTitle from '@/components/BuildModalTitle';
import AddOrEditPrice from './AddOrEditPrice';
import ReactDataGrid from 'react-data-grid';
const FormItem = Form.Item;
const { confirm } = Modal;

const RadioButton = Radio.Button;
const { Text } = Typography;
const RadioGroup = Radio.Group;

@connect(({ calendar, loading,global }) => ({
  calendar,
  global,
  loading: loading.models.calendar,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: [],
      selectedRowKeys: [],
      btnLoading:false,
      nowDate:moment().format("YYYY-MM-DD")
    };
  }


  componentDidMount() {

    const { dispatch } = this.props;
    const {
      calendar: { pageLoaded, scrollData },
    } = this.props;
    console.log('pageLoaded', pageLoaded);
    const table = document.querySelector('.react-grid-Canvas');
    if (pageLoaded) {
      // setTimeout(() => {
      //   table.scrollTop = scrollData.y;
      //   table.scrollLeft = scrollData.x;
      // }, 0);

    } else {
      const {
        calendar: { searchParams },
      } = this.props;
      console.log('searchParams', searchParams);
      dispatch({
        type: 'calendar/fetch',
        payload: searchParams,
        callback: () => {
          const { dispatch } = this.props;
          dispatch({
            type: 'calendar/changeLoaded',
          });
        },
      });

    }
    window.addEventListener('resize', this.resize);
    // table.addEventListener('scroll', debounce(this.scroll, 150));
  }



  componentWillUnmount() {
    console.log('componentWillUnmount');
    window.removeEventListener('resize', this.resize);
    return;
    const table = document.querySelector('.ant-table-body');
    table.removeEventListener('scroll', debounce(this.scroll, 300));
  }

  handleSearch = (values, cb) => {
    console.log('handleSearch', values);
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'calendar/fetch',
      payload: {
        ...values,
      },
      callback() {
        console.log('handleSearch callback');
        if (cb) cb();
      },
    });
  };
  handleEdit=()=>{
    const formValues = this.EditForm.props.form.getFieldsValue();
    console.log('formValues',formValues)
  }
  changeCalendar=(date)=>{
    console.log(date)
    const {
      calendar: { searchParams },
    } = this.props;
    if(moment(searchParams.nowDate).format("YYYY-MM-DD")===moment(date).format("YYYY-MM-DD")){
      console.log('日期相同');
      return false
    }
    this.handleSearch({
      nowDate:moment(date).format("YYYY-MM-DD")
    })
  }
  render() {
    const that = this;
    const {
      calendar: { data, loading, tableY, meta, searchParams, selectedRowKeys, additional },
      global:{gridTableW}
    } = this.props;

    function getListData(value) {
      let listData;
      switch (value.date()) {
        case 1:
          listData = [
            { type: '-1', content: '今日需要完成任务1' },
            { type: '1', content: '今日需要完成任务2' },
          ];
          break;
        case 5:
          listData = [
            { type: '-1', content: '今日需要完成任务1' },
            { type: '1', content: '今日需要完成任务2.' },
          ];
          break;
        case 15:
          listData = [
            { type: '1', content: '今日需要完成任务1' },
            { type: '1', content: '今日需要完成任务2.' },
          ];
          break;
        case 22:
          listData = [
            { type: '1', content: '今日需要完成任务1' },
            { type: '1', content: '今日需要完成任务2' },
          ];
          break;
        default:
      }
      return listData || [];
    }
    function dateCellRender(value) {
      const listData = getListData(value);
      return (
        <div className="events" onClick={()=>{
          that.setState({
            nowDate:moment(value).format('YYYY-MM-DD'),
            editRecord:listData,
            editModal:true,
          })
        }}>
          {listData.map(item => (
            <div key={item.content} title={item.content} className={Number(item.type)===1?"default":"error" }>
              {item.content}
            </div>
          ))}
        </div>
      );
    }
    return <div className="custom-card">
      <div className="table-title"><span className={'title-item'}>个人日历</span>
      </div>
      <div className="table-page" style={{padding:'0'}}>
          <Calendar  value={moment(searchParams.nowDate)} dateCellRender={dateCellRender}
                     onChange={this.changeCalendar}
                     headerRender={({ value, type, onChange, onTypeChange }) => {
                       const start = 0;
                       const end = 12;
                       const monthOptions = [];

                       const current = value.clone();
                       const localeData = value.localeData();
                       const months = [];
                       for (let i = 0; i < 12; i++) {
                         current.month(i);
                         months.push(localeData.monthsShort(current));
                       }

                       for (let index = start; index < end; index++) {
                         monthOptions.push(
                           <Select.Option className="month-item" key={`${index}`}>
                             {months[index]}
                           </Select.Option>,
                         );
                       }
                       const month = value.month();

                       const year = value.year();
                       const options = [];
                       for (let i = year - 10; i < year + 10; i += 1) {
                         options.push(
                           <Select.Option key={i} value={i} className="year-item">
                             {i}年
                           </Select.Option>,
                         );
                       }
                       return (
                         <div style={{ padding: '10px 10px 0' }}>
                           <Row type="flex" justify="space-between">
                             <Col>
                               <Select
                                 style={{marginRight:'10px'}}
                                 dropdownMatchSelectWidth={false}
                                 className="my-year-select"
                                 onChange={newYear => {
                                   const now = value.clone().year(newYear);
                                   onChange(now);
                                 }}
                                 value={String(year)}
                               >
                                 {options}
                               </Select>
                               <Select
                                 style={{marginRight:'10px'}}
                                 dropdownMatchSelectWidth={false}
                                 value={String(month)}
                                 onChange={selectedMonth => {
                                   const newValue = value.clone();
                                   newValue.month(parseInt(selectedMonth, 10));
                                   onChange(newValue);
                                 }}
                               >
                                 {monthOptions}
                               </Select>
                               <Button type={'primary'} icon={'rollback'} onClick={()=>{
                                 onChange(moment());
                               }}>返回今天</Button>
                             </Col>
                           </Row>
                         </div>
                       );
                     }}
          />


      </div>
      <Modal
        title={<BuildModalTitle visible={this.state.editModal} modalClass="editModal"
                                title={`${this.state.nowDate} 事务`}/>}
        destroyOnClose
        visible={this.state.editModal}
        centered
        onOk={this.handleEdit}
        okButtonProps={{loading:this.state.btnLoading}}
        className="editModal"
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        onCancel={() => {
          this.setState({ editModal: false, editRecord: {} });
        }}

      >
       <AddOrEditPrice
          editRecord={this.state.editRecord}
          wrappedComponentRef={(inst) => this.EditForm = inst}
        />

      </Modal>
    </div>;
  }
}

export default BasicList;
